package com.yeyouluo.zk;

import org.I0Itec.zkclient.ZkClient;

public class MyTimeServer {

    public final static String ZK_ADDR = "linux121:2181,linux122:2181,linux123:2181";
    public static final String SERVERS_PATH = "/servers";
    private String ip;
    private int port;
    private TimeService timeService;
    private ZkClient zkClient;

    public MyTimeServer(String ip, int port) {
        this.ip = ip;
        this.port = port;
        this.timeService = new TimeService(port);
        this.zkClient = new ZkClient(ZK_ADDR);
    }

    public static void main(String[] args) {
        MyTimeServer myTimeServer = new MyTimeServer(args[0], Integer.parseInt(args[1]));
        myTimeServer.connectZk();
        myTimeServer.registerServerInfo();
        myTimeServer.exposeService();
    }

    public void connectZk() {
        if (!zkClient.exists(SERVERS_PATH)) {
            zkClient.createPersistent(SERVERS_PATH);
        }
    }

    public void registerServerInfo() {
        //创建临时顺序节点
        String path = zkClient.createEphemeralSequential(SERVERS_PATH + "/server", ip + ":" + port);
        System.out.println("---->>> 服务器注册成功，ip=" + ip + ";port =" + port + ";节点路径信息=" + path);
    }

    public void exposeService() {
        timeService.start();
    }
}
